﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Internal;
using System.Globalization;

namespace System.ComponentModel.Composition
{
    internal static class MetadataViewProvider
    {
        public  static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
        {
            Type metadataViewType = typeof(TMetadataView);

            // If the Metadata dictionary is cast compatible with the passed in type
            if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object>)))
            {
                return (TMetadataView)metadata;
            }

            // Otherwise generate a proxy
            if (metadataViewType.IsInterface)
            {
                Type proxyType = MetadataViewGenerator.GenerateView(metadataViewType);
                return (TMetadataView)Activator.CreateInstance(proxyType, new object[] { metadata });
            }

            // The Metadata View can not be constructed so we must throw an ArgumentException
            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Strings.CannotCreateMetadataView, metadataViewType.FullName, "TMetadataView"));
        }

        public static bool IsViewTypeValid(Type metadataViewType)
        {
            Assumes.NotNull(metadataViewType);

            // If the Metadata dictionary is cast compatible with the passed in type
            if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object>)))
            {
                return true;
            }

            if (metadataViewType.IsInterface)
            {
                return true;
            }

            return false;
        }
    }
}
